import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:sonora/bloc/base/sj_base_bloc.dart';
import 'package:sonora/bloc/blockList/sj_block_list_event.dart';
import 'package:sonora/bloc/blockList/sj_block_list_state.dart';
import 'package:sonora/bloc/medal/sj_medal_event.dart';
import 'package:sonora/bloc/medal/sj_medal_state.dart';
import 'package:sonora/models/sj_login_response_data.dart';
import 'package:sonora/models/sj_medal_data.dart';
import 'package:sonora/models/sj_response_data.dart';
import 'package:sonora/repository/sj_medal_repository.dart';
import 'package:sonora/utils/sj_medal_utils.dart';
import 'package:sonora/utils/sj_storage_utils.dart';
import 'package:sonora/views/dialog/sj_medal_obtain_dailog.dart';

class SjMedalBloc extends SjBaseBloc<SjMedalEvent, SjMedalState> {
  final SjMedalRepository repository;
  SjMedalBloc(this.repository) : super(SjMedalState()) {
    on<SjMedalEventInitial>(_onInitial);
    on<SjMedalEventLoaded>(_onLoadedData);
    on<SjMedalEventLoadedUserInfo>(_onLoadUserInfo);
    on<SjMedalEventLoadedMedal>(_onLoadedMedal);
    on<SjMedalEventObtain1Medal>(_onObtain1Medal);
    on<SjMedalEventObtain2Medal>(_onObtain2Medal);
    on<SjMedalEventObtain3Medal>(_onObtain3Medal);
    on<SjMedalEventReviewModeConsume>(_onReviewModeConsume);
  }

  FutureOr<void> _onInitial(
      SjMedalEventInitial event, Emitter<SjMedalState> emit) async {
    emit(state.copyWith(loading: true));
  }

  FutureOr<void> _onLoadedData(
      SjMedalEventLoaded event, Emitter<SjMedalState> emit) async {}

  FutureOr<void> _onObtain1Medal(
      SjMedalEventObtain1Medal event, Emitter<SjMedalState> emit) async {
    List<SjMedalData> list = List.from(state.medalList ?? []);
    if (list.isEmpty) return;
    SjMedalData medalData = list.first;
    SjMedalData result = medalData.copyWith(isObtain: true);
    int index = list.indexOf(medalData);
    list.replaceRange(index, index + 1, [result]);
    SjMedalUtils.instance.saveMedalList(list);
    emit(state.copyWith(medalList: list, medal1IsObtain: result.isObtain));
  }

  FutureOr<void> _onObtain2Medal(
      SjMedalEventObtain2Medal event, Emitter<SjMedalState> emit) async {}

  FutureOr<void> _onObtain3Medal(
      SjMedalEventObtain3Medal event, Emitter<SjMedalState> emit) async {}

  FutureOr<void> _onLoadedMedal(
      SjMedalEventLoadedMedal event, Emitter<SjMedalState> emit) async {
    List<SjMedalData>? list = await SjMedalUtils.instance.medalList;

    if (list != null && list.length > 2) {
      emit(state.copyWith(
          medalList: list,
          medal1IsObtain: list[0].isObtain,
          medal2IsObtain: list[1].isObtain,
          medal3IsObtain: list[2].isObtain,
          medal1IsUpgrade: list[0].isUpgrade,
          medal2IsUpgrade: list[1].isUpgrade,
          medal3IsUpgrade: list[2].isUpgrade));
    } else {
      emit(state.copyWith(medalList: list));
    }
  }

  FutureOr<void> _onLoadUserInfo(
      SjMedalEventLoadedUserInfo event, Emitter<SjMedalState> emit) async {
    emit(state.copyWith(loading: true));
    try {
      SjLoginData? loginData = await SjStorageUtils.getLoginInfo();
      String userId = '';
      if (loginData != null && loginData.userInfo != null) {
        userId = loginData.userInfo?.userId ?? '';
      }
      if (state.userInfoData == null) {
        SjUserDetailData? userDetail = await SjStorageUtils.getUserDetail();
        if (userDetail != null) {
          emit(state.copyWith(userInfoData: userDetail, loading: false));
        }
      }
      SjResponseData responseData = await repository.getUserInfo(userId);
      if (responseData.data != null && responseData.success != null && responseData.success == true ) {
        Map<String, dynamic> jsonMap = responseData.data;
        SjUserDetailData userDetailData = SjUserDetailData.fromJson(jsonMap);
        emit(state.copyWith(userInfoData: userDetailData, loading: false));
        SjStorageUtils.saveUserDetail(jsonMap);
      }
    } catch (e) {
      emit(state.copyWith(loading: false, errorMsg: e.toString()));
    }
  }

  FutureOr<void> _onReviewModeConsume(
      SjMedalEventReviewModeConsume event, Emitter<SjMedalState> emit) async {
    emit(state.copyWith(loading: true));
    try {
      SjResponseData responseData =
          await repository.reviewModeConsume(event.outlay);
      if (responseData.success != null && responseData.success == true) {
        List<SjMedalData> list = List.from(state.medalList ?? []);
        if (list.isEmpty) return;
        SjMedalData? medalData;
        if (event.outlay == 25) {
          medalData = list.first;
        } else if (event.outlay == 30) {
          medalData = list[1];
        } else if (event.outlay == 35) {
          medalData = list[2];
        }
        if (medalData == null) return;
        SjMedalData result = medalData.copyWith(isUpgrade: true);
        int index = list.indexOf(medalData);
        list.replaceRange(index, index + 1, [result]);
        SjMedalUtils.instance.saveMedalList(list);
        String assetPath = 'assets/images/xz_bg_y_1.png';
        if (event.outlay == 25) {
          emit(state.copyWith(
              medalList: list,
              medal1IsUpgrade: result.isUpgrade,
              loading: false,
              errorMsg: null));
        } else if (event.outlay == 30) {
          emit(state.copyWith(
            medalList: list,
            medal2IsUpgrade: result.isUpgrade,
            loading: false,
          ));
          assetPath = 'assets/images/xz_bg_y_2.png';
        } else if (event.outlay == 35) {
          emit(state.copyWith(
            medalList: list,
            medal3IsUpgrade: result.isUpgrade,
            loading: false,
          ));
          assetPath = 'assets/images/xz_bg_y_3.png';
        }
        event.callback.call();
      } else {
        emit(state.copyWith(loading: false, errorMsg: responseData.msg ?? ''));
      }
    } catch (e) {
      emit(state.copyWith(loading: false, errorMsg: e.toString()));
    }
  }
}
